package com.kedacom.ctsp.authority.vo;

import com.alibaba.fastjson.JSONObject;
import com.kedacom.ctsp.authority.entity.Person;
import com.kedacom.ctsp.authority.entity.Role;
import com.kedacom.ctsp.authority.entity.User;
import com.kedacom.ctsp.lang.mapper.BeanMapper;
import com.kedacom.ctsp.lang.mapper.BeanMapperException;
import com.kedacom.ctsp.lang.mapper.CollComponentType;
import com.kedacom.ctsp.web.vo.AbstractCrudVO;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户
 *
 * @author
 */
@Data
@ApiModel("用户")
public class SimpleUserVO extends AbstractCrudVO<User, String> implements UserVO {

    private String id;

    private String name;

    private String username;

    private String password;

    @CollComponentType(RoleVO.class)
    private Set<RoleVO> roles;

    /**
     * 用户对应的person
     */
    private PersonVO person;
    /**
     * 扩展字段
     */
    private String extendedField;

    @Override
    public UserVO convertFrom(User source) throws IllegalFormatException {
        UserVO vo = super.convertFrom(source);
        if (CollectionUtils.isNotEmpty(source.getRoles())) {
            List<Role> roleList = new ArrayList<>(source.getRoles());
            // 再次按序号排序
            roleList.sort(((o1, o2) -> o1.compareTo(o2)));
            Set<RoleVO> roles = new LinkedHashSet<>();
            roleList.stream().forEach(r -> {
                Optional<RoleVO> optional = BeanMapper.newInstance(RoleVO.class);
                RoleVO rvo = optional.get().convertFrom(r);
                roles.add(rvo);
            });
            vo.setRoles(roles);
        }

        return vo;
    }

}
